package NetBuffer

const MAXSIZE = 65535
type NetBuffer struct{
	buf 		[]byte
	head		int32
	tail		int32
}

func NewNetBuffer()*NetBuffer{
	n := &NetBuffer{}
	n.buf = make([]byte,MAXSIZE)
	n.head = 0
	n.tail = 0
	return n
}

//可读数据长度
func (r *NetBuffer) DataLen()int32{
	return r.tail - r.head
}

//空闲空间
func (r *NetBuffer) FreeSpace()int32{
	return MAXSIZE - r.tail
}
/*
|								|							|
↑								↑							↑
head	<-readable->			tail	<-writable->		MAXSIZE
len = tail - head
freespace = MAXSIZE - tail
*/
func (r *NetBuffer) GetWritable()(buf []byte,space int32){
	return buf[r.tail:],r.FreeSpace()
}

func (r *NetBuffer) HasWrited(len int32){
	r.tail += len
}

func (r *NetBuffer) ReadData(bucket []byte,needlen int32)bool{
	if r.DataLen() < needlen{
		return false
	}

	bucket = r.buf[r.head:r.tail]
	r.head += needlen
	r.autoReset()
	return true
}

func (r *NetBuffer) PeekData(bucket []byte,needlen int32)bool{
	if r.DataLen() < needlen{
		return false
	}
	bucket = r.buf[r.head:r.head+4]
	return true
}
/*
|								|				|			|
								↑				↑			↑
								head			tail		MAXSIZE
进行调整
将head<->tail复制到最前端
|				|											|		
↑				↑											↑
head			tail										MAXSIZE
*/

func (r *NetBuffer) Reset(){
	len := r.tail - r.head

	//前端空间是否足够
	if len > r.head{
		return
	}

	copy(r.buf[0:],r.buf[r.head:len])
	r.head = 0
	r.tail = len
}

func (r *NetBuffer) autoReset(){
	middle := int32(MAXSIZE/2)
	if r.head >= middle{
		r.Reset()
	}
}


